package com.spica.spicaschool.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.asLiveData
import androidx.lifecycle.distinctUntilChanged
import androidx.lifecycle.switchMap
import com.spica.spicaschool.base.LiveCoroutinesViewModel
import com.spica.spicaschool.bean.PageEntity
import com.spica.spicaschool.bean.diary.Diary
import com.spica.spicaschool.bean.group.Group
import com.spica.spicaschool.network.ResponseList
import com.spica.spicaschool.network.repository.GroupRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import javax.inject.Inject

@HiltViewModel
class GroupViewModel @Inject constructor(
    private val groupRepository: GroupRepository
) : LiveCoroutinesViewModel() {

    private val pageEntityStateFlow: MutableStateFlow<PageEntity> = MutableStateFlow(PageEntity())

    private lateinit
    var _groupsLiveData: LiveData<ResponseList<Group>>

    val groupsLiveData: LiveData<ResponseList<Group>>
        get() = _groupsLiveData.distinctUntilChanged()

    /**
     * 初始化
     */
    fun fetchDiaryList(
        token: String,
        onStart: () -> Unit,
        onComplete: () -> Unit,
        onError: (String?) -> Unit
    ) {
        //每次页面切换时刷新数据
        _groupsLiveData = pageEntityStateFlow.asLiveData().switchMap { pageEntity ->
            groupRepository
                .fetchGroups(pageEntity, token, onStart, onComplete, onError)
                .asLiveDataOnViewModelScope()//绑定生命周期
        }
    }


    /**
     * 切换页码
     */
    fun pageChanged(pageEntity: PageEntity) {
        pageEntityStateFlow.value = pageEntity
    }

}